<?php
/**
 * Loader class.
 * This class contain static functions for auto loading other classes.
 *
 * @package OWL
 * @subpackage Core
 * @author KeiMOon
 * @since 1.0
 */

class Owl_Loader {
    /**
     * Method for loading class based on class name
     *
     * @param string $class
     * @return void
     * @throws Error
     */

    static function load_class($class) {

        self::_securityCheck($class);
        /* Check if class has been included */
        if (class_exists($class)) {
            return;
        }
        /* Determining filename and include it */
        $file = str_replace("_", "-", strtolower($class)).".php";

        if (file_exists($file)) {
            include_once ($file);
            return;
        }
        else {
            $file_exist = false;
            $include_path_array = Owl_Format::add_trailing_slash_deep(explode(PATH_SEPARATOR, get_include_path()));
            foreach($include_path_array as $include_path) {
                if (!file_exists($include_path.$file)) {
                    continue;
                }
                else {
                    $file_exist = true;
                    break;
                }
            }
            if ($file_exist) {
                include_once ($file);
                return;
            }
            else {
                die("The file $file does not exist in the include paths");
            }
        }
    }

    /**
     * Method for autoloading class
     *
     * @param string $class
     * @return bool
     */

    static function autoload($class) {
        try {
            self::load_class($class);
            return true;
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }

    static function register_autoload() {
        spl_autoload_register(array("Owl_Loader", "autoload"));
    }

    protected static function _securityCheck($filename)
    {
        /**
         * Security check
         */
        if (preg_match('/[^a-z0-9\\/\\\\_.-]/i', $filename)) {
            throw new Exception('Security check: Illegal character in filename');
        }
    }
}

